﻿package net.wangit.adm.role;

import java.util.Map;

import net.wangit.jdbc.DB;
import net.wangit.user.privilege.DataPrivilege;
import net.wangit.user.privilege.DataPrivilegeFactory;
import net.wangit.user.privilege.PrivilegeUtil;
import net.wangit.util.Checker;
import net.wangit.view.tree.Tree;


public class PrivilegeTreeUtil {

	private static final String DP_UNIT_PREFIX = "_dPu_";
	private static final String DP_ENUMERATION_PREFIX = "_dPe_";
	private static final String DATA_SQL_ICON = "/domain/dev/c/dpsql.png";
	private static final String DATA_VALUE_ICON = "/domain/dev/c/dpvalue.png";
	private String domain;
	private Map privileges;
	private boolean disabled;

	public PrivilegeTreeUtil(String domain, Map privileges, boolean disabled) {
		this.domain = domain;
		this.privileges = privileges;
		this.disabled = disabled;
	}

	public String getName(String name, String id) {
		return Checker.isEmpty(name) ? id : name;
	}

	public String getCheckedAttribute(boolean checked) {
		if (disabled)
			return checked ? "checked disabled" : "disabled";
		if (checked)
			return "checked";
		else
			return null;
	}

	public int addDataPrivileges(DB db, Tree tree, String privilegeType,
			String id) throws Exception {
		DataPrivilege dp;
		String prefix;
		if ("3".equals(privilegeType)) {
			prefix = (new StringBuilder("_dPu_")).append(id).toString();
			dp = DataPrivilegeFactory.getUnitDataPrivilege(domain, id);
		} else {
			prefix = (new StringBuilder("_dPe_")).append(id).toString();
			dp = DataPrivilegeFactory.getEnumerationDataPrivilege(domain, id);
		}
		if (dp == null)
			return 0;
		String ids[] = dp.getIds();
		String names[] = dp.getNames();
		String titles[] = dp.getTitles();
		for (int i = 0; i < ids.length; i++) {
			Tree data = new Tree();
			data.setId((new StringBuilder(String.valueOf(prefix))).append("_")
					.append(ids[i]).toString());
			data.setName(names[i]);
			data.setTitle(titles[i]);
			if ("1".equals(ids[i].substring(0, 1)))
				data.setIcon("/domain/dev/c/dpsql.png");
			else
				data.setIcon("/domain/dev/c/dpvalue.png");
			String privilege = PrivilegeUtil.getPrivilegeString(domain,
					privilegeType, id, ids[i]);
			data.setCheckValue(privilege);
			boolean checked = privileges.containsKey(privilege);
			data.setCheckAttribute(getCheckedAttribute(checked));
			tree.add(data);
		}

		return ids.length;
	}
}
